package com.qf.producer.listeners;

import com.alibaba.fastjson.JSON;
import com.qf.producer.pojo.Order;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;

@Component
//txProducerGroup是这个事务监听器的一个唯一标识.标识具体处理哪种类型的事务消息.实际业务中可能会有很多事务监听器
@RocketMQTransactionListener(txProducerGroup = "orderGroup")
public class OrderTransactionListener implements RocketMQLocalTransactionListener {

    //执行本地事务的回调（第一个回调）
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {

        try {
            //这个msg.getPaylaod()返回的数据固定是byte[]
            byte[] bys = (byte[]) msg.getPayload();
            String orderJson = new String(bys, "utf-8");

            Order order = JSON.parseObject(orderJson, Order.class);

            //进行订单生成的本地事务操作
            //order id=1 -- commit  id=2 -- rollback  id=3  unknow
            Integer id = order.getId();
            if (id == 1){
                System.out.println("生产端事务成功...下游服务执行事务操作...");
                return RocketMQLocalTransactionState.COMMIT;
            }else if(id == 2){
                System.out.println("生产端事务失败...下游服务不执行操作...");
                return RocketMQLocalTransactionState.ROLLBACK;
            }else{
                System.out.println("生产端事务状态未知...触发回查...");
                return RocketMQLocalTransactionState.UNKNOWN;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    //当半消息主题收到未知状态时，触发的状态回查回调（第二个回调）
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        System.out.println("进行事务状态回查，返回具体的回查结果.时间:" + LocalDateTime.now());
        return RocketMQLocalTransactionState.UNKNOWN;
    }
}
